package com.asdc.autoscanfiles.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.asdc.autoscanfiles.entity.EsResultDto;
import com.asdc.autoscanfiles.page.Page;
import com.asdc.autoscanfiles.service.EsResultService;

/**
 * @Author zhangbingyue
 * @Description //TODO $
 * @Date $ $ /es/save
 * @Param $
 * @return $
 **/
@RestController
@RequestMapping("/api/es")
public class EsResultController {

    @Autowired
    private EsResultService esResultService;
    @Value("${img.desPath}")
    private String desPath;

    /**
     * 数据库数据批量导入ES
     */
    @RequestMapping("/save")
    public String save() {
        esResultService.saveToEs();
        return "导入ES成功！";
    }


    /**
     * 新增/修改索引
     *
     * @return
     */
    @RequestMapping("saveOne")
    public String saveOne(@RequestBody EsResultDto productDocument) {
        esResultService.save(productDocument);
        return "success";
    }

    /**
     * 删除索引
     *
     * @return
     */
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable Integer id) {
        esResultService.delete(id);
        return "success";
    }

    /**
     * 清空索引
     *
     * @return
     */
    @RequestMapping("delete_all")
    public String deleteAll() {
        esResultService.deleteAll();
        return "success";
    }

    /**
     * 根据ID获取
     *
     * @return
     */
    @RequestMapping("get/{id}")
    public EsResultDto getById(@PathVariable Integer id) {
        return esResultService.getById(id);
    }

    /**
     * 根据获取全部
     *
     * @return
     */
    @RequestMapping("get_all")
    public List<EsResultDto> getAll() {
        return esResultService.getAll();
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8089/es/query_hit?keyword=PRE&indexName=file&fields=level3,level2
     *
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @RequestMapping("query_hit")
    public List<Map<String, Object>> queryHit(@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields) {
        String[] fieldNames = {};
        if (fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return esResultService.queryHit(keyword, indexName, fieldNames);
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8089/es/query_hit_page?keyword=PRE&indexName=file&fields=level3,level2&pageNo=1&pageSize=10
     *
     * @param pageNo    当前页
     * @param pageSize  每页显示的数据条数
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @RequestMapping("query_hit_page")
    public Page<Map<String, Object>> queryHitByPage(@RequestParam int pageNo, @RequestParam int pageSize
            , @RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields) {
        String[] fieldNames = {};
        if (fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return esResultService.queryHitByPage(pageNo, pageSize, keyword, indexName, fieldNames);
    }

    /**
     * 删除索引库
     *
     * @param indexName
     * @return
     */
    @RequestMapping("delete_index/{indexName}")
    public String deleteIndex(@PathVariable String indexName) {
        esResultService.deleteIndex(indexName);
        return "success";
    }

    /**
     * 根据参数查询所有
     * http://localhost:8089/es/list?level1=SURF&level2=ZJ&level3=PRE&beginDate=1974-01-21&endDate=1984-10-10&searchString=自&pageNo=1&pageSize=10
     * <p>
     * //     * @param level1       级别1
     * //     * @param level1       级别2
     * //     * @param level3       级别3
     * //     * @param beginDate    开始时间
     * //     * @param endDate      结束时间
     * //     * @param searchString 关键字
     * //     * @param pageNo       开始页数
     * //     * @param pageSize     每页条数
     *
     * @return
     */
    @PostMapping("/list")
    public Page<Map<String, Object>> searchList(HttpServletRequest request) {
        String indexName = "file";//索引名称
        String fields = "level1Name,level2Name,level3Name,elementName,areaName,fileName,areaNumber";//搜索字段名称，多个以“，”分割
        String level1 = request.getParameter("level1");
        String level2 = request.getParameter("level2");
        String sheng = request.getParameter("sheng");
        String beginDate = request.getParameter("beginDate");
        String beginDate1 = request.getParameter("beginDate1");
        String searchString = request.getParameter("searchString");
        Integer pageNo = Integer.parseInt(request.getParameter("pageNo"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));

        String[] fieldNames = {};
        if (fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return esResultService.findByLevelAndDate(level1, level2, sheng, beginDate, beginDate1,searchString, fieldNames, pageNo, pageSize, indexName);
    }

    @RequestMapping("/getImgPath")
    public void getImgPath(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File(desPath + request.getParameter("path"));
        if (file.exists()) {
            //读取指定路径下面的文件
            InputStream in = new FileInputStream(file);
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            //创建存放文件内容的数组
            byte[] buff = new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while ((n = in.read(buff)) != -1) {
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            //关流
            outputStream.close();
            in.close();
        }
    }
}
